package com.fqgj.xjd.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fqgj.common.api.Response;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.common.utils.HttpUtil;
import com.fqgj.common.utils.MD5;
import com.fqgj.exception.enums.BasicErrorCodeEnum;
import com.fqgj.xjd.user.client.UserPanService;
import com.fqgj.xjd.user.client.request.PanAuthResult;
import com.fqgj.xjd.user.client.request.UserPanCardPageQueryRO;
import com.fqgj.xjd.user.client.request.UserPanSaveInfo;
import com.fqgj.xjd.user.client.response.Pan;
import com.fqgj.xjd.user.client.response.UserPanInfo;
import com.fqgj.xjd.user.dao.UserAuthPanDao;
import com.fqgj.xjd.user.dao.UserKycPanAuthResultDao;
import com.fqgj.xjd.user.dao.UserOcrInfoDao;
import com.fqgj.xjd.user.dao.UserOcrPanDao;
import com.fqgj.xjd.user.entity.UserAuthPanEntity;
import com.fqgj.xjd.user.entity.UserKycPanAuthResultEntity;
import com.fqgj.xjd.user.entity.UserOcrInfoEntity;
import com.fqgj.xjd.user.entity.UserOcrPanEntity;
import com.fqgj.xjd.user.integration.UserOcrService;
import com.google.common.collect.Lists;
import com.qianli.user.domain.enums.UserAuthStatusEnum;
import com.qianli.user.exception.UserException;
import com.qianli.user.ro.UserStateCode;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 用户PanCard信息服务
 *
 * @author liuming
 * Created on 下午3:55 2018/8/17.
 */
@Service("userPanService")
public class UserPanServiceImpl implements UserPanService {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserPanServiceImpl.class);
    @Autowired
    UserAuthPanDao userAuthPanDao;
    @Autowired
    UserOcrPanDao userOcrPanDao;
    @Autowired
    UserOcrService userOcrService;
    @Autowired
    UserKycPanAuthResultDao userKycPanAuthResultDao;
    @Autowired
    UserOcrInfoDao userOcrInfoDao;

    @Override
    public Response<UserPanInfo> getByUserCode(String userCode) {
        UserAuthPanEntity userAuthPanEntity = userAuthPanDao.selectUserPanByUserCode(userCode);
        if (userAuthPanEntity == null) {
            return Response.ok().putData(null);
        }
        UserPanInfo userPanInfo = new UserPanInfo();
        BeanUtils.copyProperties(userAuthPanEntity, userPanInfo);
        return Response.ok().putData(userPanInfo);
    }

    /**
     * 获取ocr扫描pan信息
     */
    @Override
    public Response<Pan> getOcrInfoByUserCode(String userCode) {
        if (StringUtils.isEmpty(userCode)) {
            throw new UserException(UserStateCode.PARAMETER_LACK);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("userCode", userCode);
        map.put("deleted", "0");
        List<UserOcrPanEntity> userOcrPanEntities = userOcrPanDao.selectByParams(map);
        Pan pan = new Pan();
        //没有保存过ocr信息
        if (null == userOcrPanEntities || userOcrPanEntities.isEmpty() || !userOcrPanEntities.get(0).getStatus().equals(UserAuthStatusEnum.AUTHORIZED.getStatus())) {
            Map<String, Object> map2 = new HashMap<>();
            map.put("userCode", userCode);
            map.put("ocrType", "PAN_FRONT");
            map.put("deleted", "0");
            List<UserOcrInfoEntity> userOcrInfoEntityList = userOcrInfoDao.selectByParams(map2);
            if (CollectionUtils.isNotEmpty(userOcrInfoEntityList)) {
                try {
                    String ocrUrl = userOcrInfoEntityList.get(userOcrInfoEntityList.size() - 1).getOcrResultUrl();
                    JSONObject jsonObject = JSON.parseObject(HttpUtil.getPage(ocrUrl));
                    JSONObject card = jsonObject.getJSONArray("results").getJSONObject(0).getJSONObject("card_info");
                    pan.setName(card.getString("name"));
                    pan.setFather(card.getString("father_name"));
                    pan.setDate(card.getString("date_info"));
                    pan.setPanNo(card.getString("card_no"));
                    LOGGER.info("ocrForPan,通过userOcrInfo获取信息成功,pan:{},userCode:{}", JSON.toJSONString(pan), userCode);
                } catch (Exception e) {
                    LOGGER.info("ocrForPan,已废弃2,userCode:{}", userCode, e);
                    return Response.error("方法废弃");
                }
            } else {
                LOGGER.info("ocrForPan,已废弃,userCode:{}", userCode);
                return Response.error("方法废弃");
            }
        } else {
            UserOcrPanEntity userOcrPanEntity = userOcrPanEntities.get(0);
            BeanUtils.copyProperties(userOcrPanEntity, pan);
        }
        return Response.ok(pan);
    }

    /**
     * 移除ocr扫描pan信息
     *
     * @param userCode
     */
    @Override
    public Response removePanOcrInfo(String userCode) {
        userOcrPanDao.deleteByUserCode(userCode);
        return Response.ok();
    }

    /**
     * 根据panCardId获取用户PanCard信息
     */
    @Override
    public Response<UserPanInfo> getByPanNo(String panCard) {
        UserAuthPanEntity userAuthPanEntity = userAuthPanDao.selectUserPanByPanNo(panCard);
        if (userAuthPanEntity == null) {
            return Response.ok().putData(null);
        }
        UserPanInfo userPanInfo = new UserPanInfo();
        BeanUtils.copyProperties(userAuthPanEntity, userPanInfo);
        return Response.ok().putData(userPanInfo);
    }

    @Override
    public Response<List<UserPanInfo>> getListByPanNo(String panCard) {
        if (StringUtils.isEmpty(panCard)) {
            return Response.ok().putData(null);
        }
        List<UserAuthPanEntity> userAuthPanEntities = userAuthPanDao.selectUserPansByPanNo(panCard);
        if (CollectionUtils.isEmpty(userAuthPanEntities)) {
            return Response.ok().putData(null);
        }
        List<UserPanInfo> userPanInfos = Lists.newArrayList();
        for (UserAuthPanEntity entity : userAuthPanEntities) {
            UserPanInfo userPanInfo = new UserPanInfo();
            BeanUtils.copyProperties(entity, userPanInfo);
            userPanInfos.add(userPanInfo);
        }
        return Response.ok().putData(userPanInfos);
    }

    @Override
    public Response<List<UserPanInfo>> getListByMD5PanNo(String md5PanCard) {
        List<UserAuthPanEntity> userAuthPanEntities = userAuthPanDao.selectUserPansByMD5PanNo(md5PanCard);
        if (CollectionUtils.isEmpty(userAuthPanEntities)) {
            return Response.ok().putData(null);
        }
        List<UserPanInfo> userPanInfos = Lists.newArrayList();
        for (UserAuthPanEntity entity : userAuthPanEntities) {
            UserPanInfo userPanInfo = new UserPanInfo();
            BeanUtils.copyProperties(entity, userPanInfo);
            userPanInfos.add(userPanInfo);
        }
        return Response.ok().putData(userPanInfos);
    }

    @Override
    public Response addUserPan(UserPanSaveInfo userPanSaveInfo) {
        String userCode = userPanSaveInfo.getUserCode();
        UserAuthPanEntity updateEntity = new UserAuthPanEntity();
        UserAuthPanEntity userAuthPanEntity = userAuthPanDao.selectUserPanByUserCode(userCode);
        if (Objects.nonNull(userAuthPanEntity)) {
            updateEntity.setId(userAuthPanEntity.getId());
            updateEntity.setCardNo(userPanSaveInfo.getCardNo());
            if (StringUtils.isNotBlank(userPanSaveInfo.getCardNo())) {
                updateEntity.setMd5CardNo(MD5.md5(userPanSaveInfo.getCardNo()));
            }
            updateEntity.setCardUrl(userPanSaveInfo.getCardUrl());
            updateEntity.setRefNum(userPanSaveInfo.getRefNum());
            updateEntity.setPanStatus(userPanSaveInfo.getPanStatus());
            updateEntity.setUserCode(userCode);
            updateEntity.setStatusCode(userPanSaveInfo.getStatusCode());
            updateEntity.setManualCardNo(userPanSaveInfo.getManualCardNo());
            userAuthPanDao.updateByPrimaryKey(updateEntity);
        } else {
            userAuthPanEntity = new UserAuthPanEntity();
            BeanUtils.copyProperties(userPanSaveInfo, userAuthPanEntity);
            if (StringUtils.isNotBlank(userPanSaveInfo.getCardNo())) {
                userAuthPanEntity.setMd5CardNo(MD5.md5(userPanSaveInfo.getCardNo()));
            }
            userAuthPanDao.insert(userAuthPanEntity);
        }
        return Response.ok();
    }

    @Override
    public Response updatePanStatusAndUrl(UserPanSaveInfo userPanSaveInfo) {
        if (StringUtils.isEmpty(userPanSaveInfo.getPanStatus()) || StringUtils.isEmpty(userPanSaveInfo.getUserCode())) {
            return Response.error(UserStateCode.PARAMETER_LACK);
        }
        String userCode = userPanSaveInfo.getUserCode();
        UserAuthPanEntity userAuthPanEntity = userAuthPanDao.selectUserPanByUserCode(userCode);
        if (userAuthPanEntity == null) {
            return Response.error(UserStateCode.USER_AUTH_PANCARD_NOT_EXISTS);
        }
        userAuthPanEntity.setPanStatus(userPanSaveInfo.getPanStatus());
        userAuthPanEntity.setCardUrl(org.apache.commons.lang3.StringUtils.isBlank(userPanSaveInfo.getCardUrl()) ? "" : userPanSaveInfo.getCardUrl());
        userAuthPanDao.updatePanStatusAndUrl(userAuthPanEntity);
        return Response.ok();
    }

    @Override
    public Response addPanAuthResult(PanAuthResult panAuthResult) {
        if (StringUtils.isBlank(panAuthResult.getUserCode())) {
            return Response.error(UserStateCode.PARAMETER_LACK);
        }

        UserKycPanAuthResultEntity oldEntity = userKycPanAuthResultDao.selectByUserCode(panAuthResult.getUserCode());
        if (oldEntity != null) {
            oldEntity.setFirstName(panAuthResult.getFirstName());
            oldEntity.setMiddleName(panAuthResult.getMiddleName());
            oldEntity.setLastName(panAuthResult.getLastName());
            oldEntity.setPanNumber(panAuthResult.getPanNumber());
            oldEntity.setPanStatus(panAuthResult.getPanStatus());
            oldEntity.setMessage(panAuthResult.getMessage());
            oldEntity.setStatusCode(panAuthResult.getStatusCode());
            userKycPanAuthResultDao.updateByPrimaryKey(oldEntity);
            return Response.ok();
        }

        UserKycPanAuthResultEntity newEntity = new UserKycPanAuthResultEntity();
        BeanUtils.copyProperties(panAuthResult, newEntity);
        userKycPanAuthResultDao.insert(newEntity);
        return Response.ok();
    }

    @Override
    public Response<PanAuthResult> getPanAuthResultByUserCode(String userCode) {
        if (StringUtils.isBlank(userCode)) {
            return Response.error(UserStateCode.PARAMETER_LACK);
        }

        UserKycPanAuthResultEntity entity = userKycPanAuthResultDao.selectByUserCode(userCode);
        if (entity == null) {
            return Response.error(UserStateCode.USER_NOT_EXITS);
        }

        PanAuthResult panAuthResult = new PanAuthResult();
        BeanUtils.copyProperties(entity, panAuthResult);
        return Response.ok(panAuthResult);
    }

    @Override
    public Response removePanAuthResult(String userCode) {
        if (StringUtils.isBlank(userCode)) {
            return Response.error(UserStateCode.PARAMETER_LACK);
        }

        UserKycPanAuthResultEntity entity = userKycPanAuthResultDao.selectByUserCode(userCode);
        if (entity == null) {
            return Response.error(UserStateCode.USER_NOT_EXITS);
        }

        Integer integer = userKycPanAuthResultDao.deleteByPrimaryKey(entity.getId());
        return Response.ok();
    }

    @Override
    public Response<List<UserPanInfo>> getListByPage(UserPanCardPageQueryRO userPanCardPageQueryRO) {
        if (userPanCardPageQueryRO == null || userPanCardPageQueryRO.getEndDate() == null) {
            return Response.error(BasicErrorCodeEnum.PARAM_NOT_COMPLETE, "param can not be empty");
        }
        List<UserAuthPanEntity> userAuthPanEntities = userAuthPanDao.selectListByPage(userPanCardPageQueryRO.getPage(), userPanCardPageQueryRO.getEndDate());
        List<UserPanInfo> userPanInfoList = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(userAuthPanEntities)) {
            for (UserAuthPanEntity entity : userAuthPanEntities) {
                UserPanInfo userPanInfo = new UserPanInfo();
                BeanUtils.copyProperties(entity, userPanInfo);
                userPanInfoList.add(userPanInfo);
            }
        }
        return Response.ok().putData(userPanInfoList);
    }
}
